class PopupManager {
  constructor() {
    this.isRunning = false;
    this.init();
  }

  async init() {
    await this.loadSettings();
    this.bindEvents();
    this.updateUI();
    
    // 监听来自background的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.type === 'NEW_MESSAGE') {
        this.showNewMessage(request.data.data);
      }
    });
  }

  async loadSettings() {
    const result = await chrome.storage.sync.get([
      'apiUrl',
      'pollInterval',
      'isRunning',
      'lastMessageId'
    ]);
    
    document.getElementById('apiUrl').value = result.apiUrl || 'https://api.example.com/messages';
    document.getElementById('pollInterval').value = result.pollInterval || 30;
    this.isRunning = result.isRunning || false;
    
    // 获取当前状态
    const status = await this.sendMessageToBackground('GET_STATUS');
    if (status) {
      this.isRunning = status.isRunning;
    }
  }

  bindEvents() {
    document.getElementById('startBtn').addEventListener('click', () => this.startPolling());
    document.getElementById('stopBtn').addEventListener('click', () => this.stopPolling());
    document.getElementById('testBtn').addEventListener('click', () => this.testNotification());
    
    // 保存设置变化
    document.getElementById('apiUrl').addEventListener('change', () => this.saveSettings());
    document.getElementById('pollInterval').addEventListener('change', () => this.saveSettings());
  }

  async startPolling() {
    const apiUrl = document.getElementById('apiUrl').value;
    const pollInterval = parseInt(document.getElementById('pollInterval').value);
    
    if (!apiUrl) {
      alert('请先设置API地址');
      return;
    }
    
    if (pollInterval < 5) {
      alert('检查间隔不能小于5秒');
      return;
    }
    
    await this.saveSettings();
    
    const result = await this.sendMessageToBackground('START_POLLING', pollInterval);
    if (result && result.success) {
      this.isRunning = true;
      this.updateUI();
      this.updateLastCheck();
    }
  }

  async stopPolling() {
    const result = await this.sendMessageToBackground('STOP_POLLING');
    if (result && result.success) {
      this.isRunning = false;
      this.updateUI();
    }
  }

  async testNotification() {
    const result = await this.sendMessageToBackground('TEST_NOTIFICATION');
    if (result && result.success) {
      this.showNewMessage({
        content: '这是一条测试消息',
        timestamp: new Date().toISOString()
      });
    }
  }

  async saveSettings() {
    const settings = {
      apiUrl: document.getElementById('apiUrl').value,
      pollInterval: parseInt(document.getElementById('pollInterval').value)
    };
    
    await chrome.storage.sync.set(settings);
  }

  sendMessageToBackground(type, data) {
    return new Promise((resolve) => {
      chrome.runtime.sendMessage({ type, data }, resolve);
    });
  }

  updateUI() {
    const statusElement = document.getElementById('status');
    const startBtn = document.getElementById('startBtn');
    const stopBtn = document.getElementById('stopBtn');
    
    if (this.isRunning) {
      statusElement.className = 'status running';
      statusElement.querySelector('.status-text').textContent = '运行中';
      startBtn.disabled = true;
      stopBtn.disabled = false;
    } else {
      statusElement.className = 'status stopped';
      statusElement.querySelector('.status-text').textContent = '已停止';
      startBtn.disabled = false;
      stopBtn.disabled = true;
    }
  }

  showNewMessage(message) {
    debugger
    const lastMessageElement = document.getElementById('lastMessage');
    const time = new Date(message.timestamp).toLocaleTimeString();
    
    lastMessageElement.innerHTML = `
      <div><strong>${message.content}</strong></div>
      <div style="color: #85929e; margin-top: 4px;">${time}</div>
    `;
    lastMessageElement.classList.add('new');
    
    this.updateLastCheck();
    
    // 10秒后移除new样式
    setTimeout(() => {
      lastMessageElement.classList.remove('new');
    }, 10000);
  }

  updateLastCheck() {
    const lastCheckElement = document.getElementById('lastCheck');
    lastCheckElement.textContent = `最后检查: ${new Date().toLocaleTimeString()}`;
  }
}

// 初始化popup
document.addEventListener('DOMContentLoaded', () => {
  new PopupManager();
});